// Package handler
// Author liuzhiyong
// Date 2023/11/17
// Description 处理rpc请求, Rpc的入口
package handler

import (
	"context"
	"fmt"
	"gitee.com/liu_zy_developer/go_stock_service/biz/stock"
	"gitee.com/liu_zy_developer/go_stock_service/proto"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// StockSrv 定义服务端实现约定的接口
type StockSrv struct {
	proto.UnimplementedStockServer
}

// SetStock 设置库存
func (s *StockSrv) SetStock(context.Context, *proto.GoodsStockInfo) (*proto.BaseResp, error) {
	return nil, status.Errorf(codes.Unimplemented, "method SetStock not implemented")
}

// GetStock 获取库存数
func (s *StockSrv) GetStock(ctx context.Context, param *proto.GoodsStockInfo) (*proto.GoodsStockInfo, error) {
	if param.GetGoodsId() <= 0 {
		return nil, status.Error(codes.InvalidArgument, "参数错误")
	}
	fmt.Printf("param:%v\n", param)
	fmt.Printf("param.GetGoodsId():%v\n", param.GetGoodsId())
	data, err := stock.GetStockByGoodsId(ctx, param.GetGoodsId())
	if err != nil {
		zap.L().Error(
			"GetStock failed",
			zap.Int64("goods_id", param.GoodsId),
			zap.Error(err),
		)
		return nil, status.Errorf(codes.Internal, "内部错误")
	}
	return data, nil
}

// ReduceStock 扣减库存
func (s *StockSrv) ReduceStock(ctx context.Context, param *proto.GoodsStockInfo) (*proto.GoodsStockInfo, error) {
	// 扣减库存
	// 参数判断
	if param.GetGoodsId() <= 0 || param.GetNum() <= 0 {
		return nil, status.Error(codes.InvalidArgument, "无效的参数")
	}
	// 扣减库存
	data, err := stock.ReduceStock(ctx, param.GetGoodsId(), param.GetNum())
	if err != nil {
		return nil, status.Errorf(codes.Internal, "扣减库存失败")
	}
	return data, nil
}
